package 拷贝目录.Test02;

import java.io.*;

public class CopyAll {
    public static void main(String[] args) {
        File srcFile = new File("D:\\Desktop\\IDEA");
        File destFile = new File("E:\\");
        copyDir(srcFile,destFile);
    }

    private static void copyDir(File srcFile, File destFile) {
        if (srcFile.isFile()){
            FileInputStream in = null;
            FileOutputStream out =null;
            try {
                in = new FileInputStream(srcFile);
                String path = (destFile.getAbsolutePath().endsWith("\\")
                        ? destFile.getAbsolutePath()
                        : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(11);
                out = new FileOutputStream(path);
                byte[] bytes = new byte[1024 * 1024];
                int readCount = 0;
                while((readCount = in.read(bytes)) != -1){
                    out.write(bytes,0,readCount);
                }
                out.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }
        File[] files = srcFile.listFiles();

        for (File file : files){
            //System.out.println(file.getAbsolutePath());
            if (file.isDirectory()){
                //System.out.println(file.getAbsolutePath());
                String srcDir = file.getAbsolutePath();
                //System.out.println(srcDir.substring(11));
                String destDir = (destFile.getAbsolutePath().endsWith("\\")
                        ? destFile.getAbsolutePath()
                        : destFile.getAbsolutePath() + "\\") + srcDir.substring(11);
                //System.out.println(destDir);

                File newFile = new File(destDir);
                if (!newFile.exists()){
                    newFile.mkdirs();
                }

            }
            copyDir(file,destFile);

        }
    }
}
